define(['jquery','vue',],function ($,Vue){
    'use strict';
    const { createEditor, createToolbar } = wangEditor;
    // 定义 Vue 组件
    const WangEditorComponent = {
        template: `
      <div class="editor-wrapper">
        <div v-if="showToolbar" ref="toolbarRef" class="toolbar"></div>
        <div ref="editorRef" class="editor"></div>
      </div>
    `,
        props: {
            modelValue: { type: String, default: '' },
            uploadConfig: { type: Object, default: () => ({}) },
            height: { type: [String, Number], default: 500 },
            showToolbar: { type: Boolean, default: true }
        },
        emits: ['update:modelValue'],
        setup(props, { emit }) {
            const editorRef = Vue.ref(null);
            const toolbarRef = Vue.ref(null);
            let editorInstance = null;
            let toolbarInstance = null;

            // 初始化逻辑
            const initEditor = () => {
                    // 注册图片上传菜单
                    // registerUploadMenu()

                // 创建编辑器实例
                editorInstance = createEditor({
                    selector: editorRef.value,
                    config: {
                        MENU_CONF:{
                            uploadImage:{
                                server: Config.upload.uploadurl,
                                fieldName: 'file',
                                customInsert: (res, insertFn) =>{
                                   console.log(res)
                                    insertFn(res.data.url,'上传成功',res.data.url)
                                }
                            }
                        },
                        placeholder: '输入内容...',
                        onChange: (editor) => {
                            emit('update:modelValue', editor.getHtml())
                            emit('change', editor.getHtml())
                        },
                    }
                });
                // console.log(editorInstance,'-------------------')

                // 创建工具栏
                if (props.showToolbar) {
                    toolbarInstance = createToolbar({
                        editor: editorInstance,
                        selector: toolbarRef.value
                    });
                }

                // 设置初始内容
                editorInstance.setHtml(props.modelValue);
            };

            // 监听外部数据变化
            Vue.watch(() => props.modelValue, (newVal) => {
                if (editorInstance && newVal !== editorInstance.getHtml()) {
                    editorInstance.setHtml(newVal);
                }
            });

            // 生命周期
            Vue.onMounted(() => initEditor());
            Vue.onBeforeUnmount(() => {
                editorInstance?.destroy();
                toolbarInstance?.destroy();
            });

            return { editorRef, toolbarRef };
        }
    };
    return WangEditorComponent
})